package com.android.clinic.app.picture;

import android.content.Context;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.clinic.app.R;
import com.android.clinic.app.picture.bean.FunctionConfig;
import com.android.clinic.app.picture.bean.LocalMedia;
import com.facebook.drawee.view.SimpleDraweeView;
import com.jiongbull.jlog.JLog;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by cheng on 2018/2/6.
 */
public class PictureImageGridAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public static final int TYPE_CAMERA = 1;
    public static final int TYPE_PICTURE = 2;

    private Context context;
    private boolean showCamera = true;
    private OnPhotoSelectChangedListener imageSelectChangedListener;
    private List<LocalMedia> images = new ArrayList<>();
    private List<LocalMedia> selectImages = new ArrayList<>();
    private boolean enablePreview;
    private boolean is_checked_num;

    public PictureImageGridAdapter(Context context, boolean enablePreview, boolean is_checked_num) {
        this.context = context;
        this.enablePreview = enablePreview;
        this.is_checked_num = is_checked_num;
    }

    public void bindImagesData(List<LocalMedia> images) {
        this.images = images;
        notifyDataSetChanged();
    }

    public void bindSelectImages(List<LocalMedia> images) {
        this.selectImages = images;

        for (LocalMedia select : selectImages) {
            JLog.e("select-images: " + select.getPath());
        }
        notifyDataSetChanged();
        subSelectPosition();
        if (imageSelectChangedListener != null) {
            imageSelectChangedListener.onChange(selectImages);
        }
    }

    public List<LocalMedia> getSelectedImages() {
        return selectImages;
    }

    public List<LocalMedia> getImages() {
        return images;
    }

    @Override
    public int getItemViewType(int position) {
        if (showCamera && position == 0) {
            return TYPE_CAMERA;
        } else {
            return TYPE_PICTURE;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_CAMERA) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_picture_camera, parent, false);
            return new HeaderViewHolder(view);
        } else {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_picture_grid_image, parent, false);
            return new ViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (getItemViewType(position) == TYPE_CAMERA) {
            HeaderViewHolder headerHolder = (HeaderViewHolder) holder;
            headerHolder.headerView.setOnClickListener(v -> {
                if (imageSelectChangedListener != null) {
                    imageSelectChangedListener.onTakePhoto();
                }
            });
        } else {
            final ViewHolder contentHolder = (ViewHolder) holder;
            final LocalMedia image = images.get(showCamera ? position - 1 : position);
            image.position = contentHolder.getAdapterPosition();
            String path = image.getPath();

            if (is_checked_num) {
                notifyCheckChanged(contentHolder, image);
            }

            selectImage(contentHolder, isSelected(image), false);

//            Log.e("path", path);
            Uri imageUri = Uri.parse("file://" + path);
            contentHolder.picture.setImageURI(imageUri);

            if (enablePreview) {//选中状态
                contentHolder.layCheck.setOnClickListener(v -> changeCheckboxState(contentHolder, image));
            }
            contentHolder.contentView.setOnClickListener(v -> changeCheckboxState(contentHolder, image));
        }
    }


    @Override
    public int getItemCount() {
        return showCamera ? images.size() + 1 : images.size();
    }

    private class HeaderViewHolder extends RecyclerView.ViewHolder {

        View headerView;

        HeaderViewHolder(View itemView) {
            super(itemView);
            headerView = itemView;
        }
    }


    private class ViewHolder extends RecyclerView.ViewHolder {

        SimpleDraweeView picture;
        TextView tvCheck;
        LinearLayout layCheck;
        View contentView;

        ViewHolder(View itemView) {
            super(itemView);
            contentView = itemView;
            picture = (SimpleDraweeView) itemView.findViewById(R.id.picture);
            tvCheck = (TextView) itemView.findViewById(R.id.tv_check);
            layCheck = (LinearLayout) itemView.findViewById(R.id.layout_check);
        }
    }

    private boolean isSelected(LocalMedia image) {
        for (LocalMedia media : selectImages) {
            if (media.getPath().equals(image.getPath())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 选择按钮更新
     */
    private void notifyCheckChanged(ViewHolder viewHolder, LocalMedia imageBean) {
        viewHolder.tvCheck.setText("");
        selectImages.stream().filter(media -> media.getPath().equals(imageBean.getPath())).forEach(media -> {
            imageBean.setNum(media.getNum());
            viewHolder.tvCheck.setText(String.valueOf(imageBean.getNum()));
        });
    }

    /**
     * 改变图片选中状态
     *
     * @param contentHolder
     * @param image
     */

    private void changeCheckboxState(ViewHolder contentHolder, LocalMedia image) {
        boolean isChecked = ((int)contentHolder.tvCheck.getTag() == 1) ? true : false;

        int maxSelectNum = FunctionConfig.SELECT_MAX_NUM;
        if (selectImages.size() >= maxSelectNum && !isChecked) {
            Toast.makeText(context, "你最多可以选择" + maxSelectNum + "张图片", Toast.LENGTH_LONG).show();
            return;
        }
        if (isChecked) {
            for (LocalMedia media : selectImages) {
                if (media.getPath().equals(image.getPath())) {
                    selectImages.remove(media);
                    subSelectPosition();
                    break;
                }
            }
        } else {
            selectImages.add(image);
            image.setNum(selectImages.size());
        }
        //通知点击项发生了改变   会有刷新效果  图片闪动
        selectImage(contentHolder, !isChecked, true);
        if (imageSelectChangedListener != null) {
            imageSelectChangedListener.onChange(selectImages);
        }
    }

    /**
     * 更新选择的顺序
     */
    private void subSelectPosition() {
        if (is_checked_num) {
            for (int index = 0, len = selectImages.size(); index < len; index++) {
                LocalMedia media = selectImages.get(index);
                media.setNum(index + 1);
                notifyItemChanged(media.position);
            }
        }
    }

    private void selectImage(ViewHolder holder, boolean isChecked, boolean isAnim) {
        if (isChecked) {
            holder.tvCheck.setTag(1);
            holder.tvCheck.setBackgroundResource(R.drawable.icon_def_checked);
        } else {
            holder.tvCheck.setTag(0);
            holder.tvCheck.setBackgroundResource(R.drawable.icon_def_check);
        }
        if (isChecked) {
            if (isAnim) {
                Animation animation = OptAnimationLoader.loadAnimation(context, R.anim.modal_in);
                holder.tvCheck.startAnimation(animation);
            }
            holder.picture.setColorFilter(ContextCompat.getColor(context,
                    R.color.image_overlay_normal), PorterDuff.Mode.SRC_ATOP);
        } else {
            holder.picture.setColorFilter(ContextCompat.getColor(context,
                    R.color.image_overlay), PorterDuff.Mode.SRC_ATOP);
        }
    }

    interface OnPhotoSelectChangedListener {
        void onTakePhoto();

        void onChange(List<LocalMedia> selectImages);

    }

    public void setOnPhotoSelectChangedListener(OnPhotoSelectChangedListener imageSelectChangedListener) {
        this.imageSelectChangedListener = imageSelectChangedListener;
    }

}
